package com.wyw.leetcode.learning.simple;

/**
 * @Title   leetcode topic 700
 * @Description 二叉搜索树中的插入
 *
 *      给定二叉搜索树（BST）的根节点 root 和要插入树中的值 value ，将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ，新值和原始二叉搜索树中的任意节点值都不同。
 *
 *      注意，可能存在多种有效的插入方式，只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果 。
 *
 * @Author Mr Wu yewen.wu.china@gmail.com
 * Update History:
 * Author        Time            Content
 */
public class Topic701 {

    public static void main(String[] args) {
        TreeNode node = new TreeNode(4);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(7);
        TreeNode node4 = new TreeNode(1);
        TreeNode node5 = new TreeNode(3);

        node.left = node2;
        node.right = node3;

        node2.left=node4;
        node2.right=node5;

        TreeNode treeNode = insertIntoBST1(node, 5);
        System.out.println("end");
    }

    public static TreeNode insertIntoBST(TreeNode root, int val) {
        if(root == null) {
            return new TreeNode(val);
        }

        TreeNode middleTree = root;

        while(middleTree!=null) {
            if(middleTree.val > val) {
                if(middleTree.left == null) {
                    middleTree.left = new TreeNode(val);
                    return root;
                } else
                    middleTree = middleTree.left;
            } else  {
                if(middleTree.right == null) {
                    middleTree.right = new TreeNode(val);
                    return root;
                }else
                    middleTree = middleTree.right;
            }
        }

        return root;
    }

    public static TreeNode insertIntoBST1(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }
        TreeNode pos = root;
        while (pos != null) {
            if (val < pos.val) {
                if (pos.left == null) {
                    pos.left = new TreeNode(val);
                    break;
                } else {
                    pos = pos.left;
                }
            } else {
                if (pos.right == null) {
                    pos.right = new TreeNode(val);
                    break;
                } else {
                    pos = pos.right;
                }
            }
        }
        return root;
    }

}
